import logging
from logging.handlers import RotatingFileHandler

import redis
from flask import Flask, g
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect

from config import config_map
from ihome.utils.commons import ReConverter

db = SQLAlchemy()
redis_store = None

# 设置日志的记录等级
logging.basicConfig(level=logging.DEBUG)  # 调试debug级别
# 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小，保存的日志文件的个数上线
file_log_handler = RotatingFileHandler('logs/log', maxBytes=1024*1024*100, backupCount=10)
# 创建日志记录格式
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
# 为刚创建的日志记录器设置日志记录格式
file_log_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_log_handler)


# 工厂模式
def create_app(config_name):
    """
    创建flask的应用对象
    :param config_name: str  配置模式的模式名  ("develop", "product")
    :return: 
    """
    app = Flask(__name__)
    config_class = config_map.get(config_name)

    app.config.from_object(config_class)

    db.init_app(app)

    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST, port=config_class.REDIS_PORT)

    Session(app)
    CSRFProtect(app)

    app.url_map.converters["re"] = ReConverter
    from ihome import api_1_0
    app.register_blueprint(api_1_0.api, url_prefix="/api/v1.0")
    from ihome import web_html
    app.register_blueprint(web_html.html)
    return app
